package com.spider.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParamBean;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtils {

	public static HttpClient getHttpClient() {
		HttpParams params = new BasicHttpParams();
		/* set User-Agent */
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);

		HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
		paramsBean.setVersion(HttpVersion.HTTP_1_1);
		paramsBean.setUseExpectContinue(false);

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
				.getSocketFactory()));

		PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(
				schemeRegistry);
		/* 设置最大连接数 */
		connectionManager.setMaxTotal(200);
		connectionManager.setDefaultMaxPerRoute(100);
		HttpClient httpClient = new DefaultHttpClient(connectionManager, params);

		httpClient.getParams().setIntParameter("http.socket.timeout", 60000);
		httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.BEST_MATCH);
		return httpClient;
	}

	/**
	 * 
	 * @param url
	 * @param headers
	 * @return
	 */
	public static HttpResponse doGet(String url, Map<String, String> headers) {
		HttpClient client = getHttpClient();
		HttpGet getMethod = new HttpGet(url);
		HttpResponse response = null;
		try {
			if (headers != null && headers.keySet().size() > 0) {
				for (String key : headers.keySet()) {
					getMethod.addHeader(key, headers.get(key));
				}
			}
			response = client.execute(getMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 
	 * @param url
	 *            请求地址
	 * @param headers
	 *            请求头部信息
	 * @param params
	 * @return
	 */
	public static HttpResponse doPost(String url, Map<String, String> headers,
			Map<String, String> params) {
		HttpClient client = getHttpClient();
		HttpPost postMethod = new HttpPost(url);
		HttpResponse response = null;
		try {
			if (headers != null && headers.keySet().size() > 0) {
				for (String key : headers.keySet()) {
					postMethod.addHeader(key, headers.get(key));
				}
			}
			List<NameValuePair> p = null;
			if (params != null && params.keySet().size() > 0) {
				p = new ArrayList<NameValuePair>();
				for (String key : params.keySet()) {
					p.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			if (p != null)
				postMethod.setEntity(new UrlEncodedFormEntity(p, HTTP.UTF_8));
			response = client.execute(postMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	/**
	 * 返回登陆的cookies
	 * 
	 * @param response
	 * @return
	 */
	public static List<Cookie> getCookies(HttpResponse response) {
		List<Cookie> cookies = null;
		Header[] hds = response.getAllHeaders();
		if (hds != null && hds.length > 0) {
			for (int i = 0; i < hds.length; i++) {
				if (hds[i].getName().equalsIgnoreCase("Set-Cookie")) {
					if (cookies == null) {
						cookies = new ArrayList<Cookie>();
					}
					String cookiestring[] = hds[i].getValue().split(";");
					String ss[] = cookiestring[0].split("=", 2);
					String cookiename = ss[0];
					String cookievalue = ss[1];
					Cookie cookie = new BasicClientCookie(cookiename,
							cookievalue);
					cookies.add(cookie);
				}
			}
		}
		return cookies;
	}

	/**
	 * 将cookies转换为字符串
	 * 
	 * @param cookies
	 * @return
	 */
	public static String setCookie2Str(List<Cookie> cookies) {
		StringBuilder builder = null;
		if (cookies != null && cookies.size() > 0) {
			builder = new StringBuilder();
			for (int j = 0; j < cookies.size(); j++) {
				Cookie c = cookies.get(j);
				builder.append(c.getName() + "=" + c.getValue());
				if (j != cookies.size() - 1)
					builder.append("; ");
			}
			return builder.toString();
		}
		return null;
	}

	/**
	 * 获得响应的头部信息
	 * 
	 * @param response
	 * @return
	 */
	public static List<Header> getReponseHeaders(HttpResponse response) {
		List<Header> headers = null;
		Header[] hds = response.getAllHeaders();
		if (hds != null && hds.length > 0) {
			headers = new ArrayList<Header>();
			for (int i = 0; i < hds.length; i++) {
				headers.add(hds[i]);
			}
		}
		return headers;
	}

	/**
	 * 设置响应的头部信息
	 * 
	 * @param headers
	 * @param request
	 */
	public static void setHeaders(Map<String, String> headers,
			HttpUriRequest request) {
		if (headers != null && headers.keySet().size() > 0) {
			for (String key : headers.keySet()) {
				request.addHeader(key, headers.get(key));
			}
		}
	}

	/**
	 * 从response中获得内容
	 * 
	 * @param response
	 * @return
	 */
	public static String getStrFromResponse(HttpResponse response) {
		if (response == null) {
			return null;
		}
		String responseText = null;
		try {
			responseText = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return responseText;
	}
}
